package com.changgou.controller;

import com.changgou.search.pojo.SkuInfo;
import com.changgou.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import com.changgou.entity.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/search")
public class SearchController {

    @Autowired
    private SearchService searchService;

    //对搜索入参带有特殊符号进行处理
    @GetMapping
    @ResponseBody
    public Map search(@RequestParam Map<String,String> searchMap){

        //特殊符号处理
        this.handlerSearchMap(searchMap);
        Map resultMap = searchService.search(searchMap);
        return resultMap;
    }

    //全文检索
    private void handlerSearchMap(Map<String,String> searchMap) {
            Set<Map.Entry<String, String>> entries = searchMap.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                if (entry.getKey().startsWith("spec_")){
                    searchMap.put(entry.getKey(),entry.getValue().replace("+","%2B"));
                }
            }
    }

    /**
     * 跳转搜索结果页面
     * @param searchMap
     * @param model
     * @return
     */
    @GetMapping("/list")
    public String list(@RequestParam Map<String,String> searchMap, Model model){
        //特殊符号处理
        this.handlerSearchMap(searchMap);

        //获取查询返回结果
        Map<String,Object> resultMap = searchService.search(searchMap);
        model.addAttribute("searchMap",searchMap);
        model.addAttribute("result",resultMap);

        //封装分页数据并返回
        Page<SkuInfo> page = new Page<SkuInfo>(Long.parseLong(String.valueOf(resultMap.get("total"))),Integer.parseInt(String.valueOf(resultMap.get("pageNum"))),Page.pageSize);
        model.addAttribute("page",page);


        //拼装url
        StringBuilder url = new StringBuilder("/search/list");
        if (searchMap != null && searchMap.size() > 0){
            //查询条件
            url.append("?");
            for (String paramKey : searchMap.keySet()) {
                if (!"sortRule".equals(paramKey) && !"sortField".equals(paramKey) && !"pageNum".equals(paramKey)){
                    url.append(paramKey).append("=").append(searchMap.get(paramKey)).append("&");
                }
            }
            String urlString = url.toString();
            urlString = urlString.substring(0,urlString.length() - 1);
            model.addAttribute("url",urlString);
        }else {
            model.addAttribute("url",url);
        }
        return "search";
    }
}
